import { G_Config } from "../config/ConfigManager"
import { G_Data } from "../data/DataCenter"
import { MeVo } from "../data/role/MeVo"
import { ConditionLink } from "../data/links/ConditionLink"


export interface IConditoinResult {
    isComplete: boolean
    cur: number
    tar: number
    reason: string
}

export enum ReasonType {
    cur_target
}

export enum ConditionEvent {
    COMPLETE = "CONDITION_COMPLETE_EVENT"
}

export class ConditionCenter {
    _conditionCache = {}
    _registerEvents = {}
    _conditionLink: ConditionLink = null
    _eventListenerHandle = {}
    _meVo = null

    private static created: boolean = false;

    constructor() {
        if (ConditionCenter.created) {
            throw new Error("ConditionCenter 是单例");
        }
        ConditionCenter.created = true;
        this.registEvent()
    }

    get meVo(): MeVo {
        if (this._meVo)
            return this._meVo
        this._meVo = G_Data.me
        return this._meVo
    }

    get conditionLink() {
        if (this._conditionLink == null)
            this._conditionLink = G_Data.me.condition
        return this._conditionLink
    }

    private registEvent() {
        //注册事件和处理函数

        // //金币数达到多少
        // this._registEvent("Event_1", this.checkCostCoin, [["Condition_1"]], "COIN_CHANGED")
        // //铁匠铺效率
        // this._registEvent("Event_2", this.checkBlacksmithCefficiency)
        // //铁匠铺人数
        // this._registEvent("Event_3", this.checkBlacksmithWorker)
        // //广告总数
        // this._registEvent("Event_5", this.checkAdTotal)
    }

    /**
     * 注册事件
     * @param event 事件tag
     * @param dealFunc 处理函数
     * @param condition 条件tag
     * @param listenEvent 监听事件
     * @param completeEvent 完成事件
     */
    private _registEvent(event, dealFunc, condition = null, listenEvent = null, completeEvent = null) {
        if (this._registerEvents[event] != null) {
            throw new Error("事件已注册");
        }

        this._registerEvents[event] = { dealFunc: dealFunc }

        //监听事件
        if (condition != null && listenEvent != null) {
            let func = null
            func = () => {
                let result = this.checkConditions(condition)
                if (result.isComplete) {
                    // app.eventCenter.off(listenEvent, this, func)
                    // app.eventCenter.event(completeEvent ? completeEvent : ConditionEvent.COMPLETE, { condition: condition, result: result })
                }
            }
            // app.eventCenter.on(listenEvent, this, func)
        }
    }

    /**
     * 检查条件数组
     * @param conditions 
     * @param isReason 
     * @returns 
     */
    public checkConditions(conditions, isReason = false, customReasomFormat?): IConditoinResult {
        let result: IConditoinResult = { isComplete: false, cur: null, tar: null, reason: "" }

        for (let i = 0; i < conditions.length; i++) { // and
            for (let index = 0; index < conditions[i].length; index++) { // or
                let condition = conditions[i][index]
                result = this.checkSingleCondition(condition, isReason, customReasomFormat)
                if (result.isComplete == true)
                    break
            }
            if (result.isComplete == false)
                return result
        }

        return result
    }

    /**
     * reason 类型
     * @param data
     * @param reasonType 
     * @returns 
     */
    getReasonByType(config, result, customReasomFormat) {
        let type = customReasomFormat.type ? customReasomFormat.type : ReasonType.cur_target

        if (type == ReasonType.cur_target) {
            if (result.cur != null && result.tar != null) {
                let color2 = "#00FF00"
                let color1 = result.isComplete ? color2 : "#ff0000"

                let template = `<color=${color1}>${result.cur}</color> <color=${color2}>/${result.tar}</color>`
                return this.replaceFormat(config["tip"], { a: template })
            }
        }
    }


    /**
     * 检查单个条件
     * @param condition 
     * @param isReason 
     * @returns 
     */
    public checkSingleCondition(condition, isReason = false, customReasomFormat?): IConditoinResult {
        let config = G_Config.condition.findData(condition)

        //读取缓存结果
        if (this._conditionCache[condition] != null || this.conditionLink.isCompletCondition(condition)) {
            let result = this._conditionCache[condition]
            if (result == null) {
                result = { isComplete: true, cur: config["param"]["target"], tar: config["param"]["target"], reason: "" }
                //加入缓存
                this._conditionCache[condition] = result
            }

            //添加reason
            if (result.reason == "" && isReason) {
                result.reason = this.getReasonByType(config, result, customReasomFormat ? customReasomFormat : {})
            }

            return result
        }

        //事件信息
        let eventInfo = this._registerEvents[config["event"]]

        if (eventInfo["dealFunc"] == null)
            throw new Error(config["event"] + ":事件函数未实现")

        //处理条件
        let result = eventInfo["dealFunc"].call(this, config)
        if (isReason) {
            result.reason = this.getReasonByType(config, result, customReasomFormat ? customReasomFormat : {})
        }

        //缓存结果
        if (result.isComplete) {
            //存数据
            this.conditionLink.addCompletCondition(condition)
            //加入缓存
            this._conditionCache[condition] = result
        }

        return result
    }

    /**
     *  格式化字符串
     * @param input 
     * @param replacements 
     * @returns 
     */
    private replaceFormat(input: string, replacements: Record<string, string>): string {
        const regex = /\${([^}]+)}/g;
        const replaced = input.replace(regex, (match, key) => {
            if (replacements.hasOwnProperty(key)) {
                return replacements[key].toString();
            } else {
                return match;
            }
        });
        return replaced;
    }

    // 检查消耗金币
    // private checkCostCoin(config): IConditoinResult {
    //     let result: IConditoinResult = { isComplete: false, cur: this.meVo.coin.value, tar: config["param"].target, reason: "" }
    //     result.isComplete = result.cur >= result.tar
    //     return result
    // }

    // // 检查铁匠铺效率
    // private checkBlacksmithCefficiency(config): IConditoinResult {
    //     let result: IConditoinResult = { isComplete: false, cur: this.meVo.blacksmith.efficiency, tar: config["param"].target, reason: "" }
    //     result.isComplete = result.isComplete = result.cur >= result.tar
    //     return result
    // }

    // // 检查铁匠铺人数
    // private checkBlacksmithWorker(config): IConditoinResult {
    //     let result: IConditoinResult = { isComplete: false, cur: this.meVo.blacksmith.peopleNum, tar: config["param"].target, reason: "" }
    //     result.isComplete = result.isComplete = result.cur >= result.tar
    //     return result
    // }

    // // 检查总的广告次数
    // private checkAdTotal(config): IConditoinResult {
    //     let result: IConditoinResult = { isComplete: false, cur: this.meVo.common.adTotal, tar: config["param"].target, reason: "" }
    //     result.isComplete = result.isComplete = result.cur >= result.tar
    //     return result
    // }

    //游戏时间达到${b}小时TODO

}
